package com.lzy.business.controller.agent;

import com.github.pagehelper.PageInfo;
import com.lzy.base.dtos.SysUserAdminDto;
import com.lzy.business.controller.BaseController;
import com.lzy.business.facade.AgencyManagementFacade;
import com.lzy.business.facade.AgentOrderInfoFacade;
import com.lzy.business.request.AgentOrderInfoRequest;
import com.lzy.business.request.AgentcashBackRecordRequest;
import com.lzy.business.response.AgentProtocolAccountDtoResponse;
import com.lzy.business.response.excel.AgentOrderReponse;
import com.lzy.business.response.excel.AgentProductOrderReponse;
import com.lzy.common.apis.AreaServiceApi;
import com.lzy.common.dtos.AreaDto;
import com.lzy.framework.component.PageBean;
import com.lzy.framework.core.excel.SimpleExcelExportUtils;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.core.utils.DateUtil;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.core.utils.StringUtil;
import com.lzy.framework.core.utils.WebUtils;
import com.lzy.framework.tools.date.DateUtils;
import com.lzy.member.apis.MemberUserServiceApi;
import com.lzy.product.apis.AgentOrderInfoServiceApi;
import com.lzy.product.apis.ProductUserServiceApi;
import com.lzy.product.constants.AgentOrderEnum;
import com.lzy.product.dtos.ProductUserDto;
import com.lzy.product.dtos.agent.AgentOrderInfoDto;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin/agent/order")
public class AgentOrderInfoController extends BaseController {

    @Autowired
    private AgentOrderInfoServiceApi agentOrderInfoServiceApi;

    @Autowired
    private AgentOrderInfoFacade agentOrderInfoFacade;

    @Autowired
    private ProductUserServiceApi productUserServiceApi;


    private static final Logger LOGGER = LoggerFactory.getLogger(AgentOrderInfoController.class);


    /**
     * 分页查询订单列表
     *
     * @param agentOrderInfoRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryOrder", method = RequestMethod.GET)
    public PageBean queryOrder(AgentOrderInfoRequest agentOrderInfoRequest) {
        if (agentOrderInfoRequest != null) {
            Pager pager = new Pager();
            pager.setPageSize(agentOrderInfoRequest.getPageSize());
            pager.setPageNum(agentOrderInfoRequest.getPageNum());
            AgentOrderInfoDto agentOrderInfoDto = new AgentOrderInfoDto();
            agentOrderInfoDto.setCreateTime(agentOrderInfoRequest.getCreateTime());
            agentOrderInfoDto.setStatus(agentOrderInfoRequest.getStatus());
            agentOrderInfoDto.setType(agentOrderInfoRequest.getType());
            agentOrderInfoDto.setEndDate(agentOrderInfoRequest.getEndTime());
            agentOrderInfoDto.setQueryStr(agentOrderInfoRequest.getQueryStr());
            /**
             * 如果是代理商，仅展示该代理商相关的订单，否则展示全部
             */
            SysUserAdminDto sysUserAdminDto = getCurrentUser();
            ProductUserDto productUserDto = productUserServiceApi.findById(sysUserAdminDto.getId());
            if (isAgent(productUserDto))
                agentOrderInfoDto.setUserId(productUserDto.getId());
            return agentOrderInfoServiceApi.query(pager, agentOrderInfoDto);
        }
        return null;
    }

    /**
     * 判断是否是代理商(体系id不为空，代理商编号不为空，协议id不为空，成为代理商时间不为空)
     *
     * @param productUserDto
     * @return
     */
    private Boolean isAgent(ProductUserDto productUserDto) {
        return productUserDto.getSystemId() != null
                && !productUserDto.getSystemId().equals("")
                && productUserDto.getAgentNumber() != null
                && !productUserDto.getAgentNumber().equals("")
                && StringUtils.isNotBlank(productUserDto.getAgentTime());
    }


    /**
     * 查看订单信息
     *
     * @param orderId
     * @return
     */
    @RequestMapping("/queryOrderById")
    @ResponseBody
    public Result queryOrderById(Long orderId) {
        return new Result(agentOrderInfoFacade.queryOrderById(orderId));
    }

    /**
     * 查看合同信息
     *
     * @param
     * @param
     */
    @RequestMapping("/queryContractByOrderId/{orderId}")
    @ResponseBody
    public Result queryContractByOrderId(@PathVariable("orderId") Long orderId) {
        return new Result(agentOrderInfoFacade.queryContractByOrderId(orderId));
    }

    /**
     * 订单导出
     *
     * @param agentOrderInfoRequest
     * @param request
     * @param response
     */
    @RequestMapping("/queryOrder/xls")
    public void queryOrderExt(AgentOrderInfoRequest agentOrderInfoRequest, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<AgentOrderInfoDto> agentOrderInfoDtoList = queryOrder(agentOrderInfoRequest).getRows();
            SimpleExcelExportUtils excelExportService = new SimpleExcelExportUtils();
            String fileName = agentOrderInfoRequest.getType().equals(AgentOrderEnum.OrderType.AgentAgreement.getCode()) ? "代理商订单" : "产品订单";
            fileName += new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".xls";
            if (!agentOrderInfoDtoList.isEmpty()) {
                HSSFWorkbook wb;
                if (agentOrderInfoRequest.getType().equals(AgentOrderEnum.OrderType.AgentAgreement.getCode())) {
                    List<AgentOrderReponse> list = DozerUtils.maps(agentOrderInfoDtoList, AgentOrderReponse.class);
                    for (AgentOrderReponse agentOrderReponse : list) {
                        agentOrderReponse.setName(agentOrderReponse.getName() + " " + agentOrderReponse.getPhone());
                    }
                    wb = excelExportService.generateExcel(list);
                } else {
                    List<AgentProductOrderReponse> list = new ArrayList<>();
                    AgentProductOrderReponse agentProductOrderReponse = new AgentProductOrderReponse();
                    for (AgentOrderInfoDto agentOrderInfoDto : agentOrderInfoDtoList) {
                        agentProductOrderReponse = DozerUtils.map(agentOrderInfoDto, AgentProductOrderReponse.class);
                        //设置订单信息
                        agentProductOrderReponse.setOrder(agentOrderInfoDto.getName() + " " + agentOrderInfoDto.getPhone());
                        if (null != agentOrderInfoDto.getCreateTime() && agentOrderInfoDto.getCreateTime().endsWith(".0")) {
                            agentProductOrderReponse.setOrder(agentProductOrderReponse.getOrder() + " " + agentOrderInfoDto.getCreateTime().substring(0, agentOrderInfoDto.getCreateTime().lastIndexOf(".")));
                        } else {
                            agentProductOrderReponse.setOrder(agentProductOrderReponse.getOrder() + " " + agentOrderInfoDto.getCreateTime());
                        }
                        agentProductOrderReponse.setShop(agentOrderInfoDto.getShopName() + " " + agentOrderInfoDto.getShopPhone());
                        agentProductOrderReponse.setProduct("订单号:" + agentOrderInfoDto.getOrderId() + " 商品名称:" + agentOrderInfoDto.getProductName() + " 数量:" + agentOrderInfoDto.getCount());
                        list.add(agentProductOrderReponse);
                    }
                    wb = excelExportService.generateExcel(list);
                }
                WebUtils.prepareDownloadFile(fileName, "application/msexcel", request, response);
                OutputStream outputStream = response.getOutputStream();
                wb.write(outputStream);
                outputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("订单导出excel失败");
        }

    }

    /**
     * 查看补贴信息
     *
     * @param agentcashBackRecordRequest
     * @return
     */
    @RequestMapping(value = "/cashBackRecord", method = RequestMethod.GET)
    @ResponseBody
    public PageBean cashBackRecord(AgentcashBackRecordRequest agentcashBackRecordRequest) {
        PageInfo pageInfo = agentOrderInfoFacade.cashBackRecord(agentcashBackRecordRequest);
        return new PageBean(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 账户信息
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/accountInformation", method = RequestMethod.GET)
    @ResponseBody
    public Result accountInformation(Long orderId) {
        AgentProtocolAccountDtoResponse agentProtocolAccountDtoResponse = agentOrderInfoFacade.accountInformation(orderId);
        return new Result(agentProtocolAccountDtoResponse);
    }


    /**
     * 页面路由
     *
     * @param pageName
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String pageRout(String pageName) {
        StringBuilder pagePath = new StringBuilder(30);
        pagePath.append("agent/order/");
        if (StringUtil.isBlank(pageName)) {
            pagePath.append("agreeOrder_list");
        } else {
            pagePath.append(pageName);
        }
        return pagePath.toString();
    }

}
